package com.carr.common.config;

import com.alibaba.fastjson.JSON;
import com.carr.common.constant.CommonConstant;
import com.carr.common.response.HttpResponse;
import com.carr.common.response.HttpResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author yulin.chen
 * @classname ExceptionHandler
 * @description TODO
 * @date 2020/9/25 16:35
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResponse bizExceptionHandler(HttpServletRequest req, Exception e) {
        if (e instanceof HttpMediaTypeNotSupportedException) {
                return HttpResponseUtil.fail(HttpResponse.NOT_SUPPORT_CONTENT_TYPE_UTF8,e.getMessage());
        }
        log.error("全局捕获到异常。"+e.getMessage(),e);
        return HttpResponseUtil.fail("全局捕获到异常。"+ (Objects.isNull(e.getMessage())? JSON.toJSONString(e) :e.getMessage()));
    }
}
